package cn.wowjoy.office.materialinspection.check.detail.add;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.AutoEditAdapter;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.AutoKeyPopup;
import cn.wowjoy.office.common.widget.BottomMenuPopupType;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.request.SubmitCheckTaskListDetailRequest;
import cn.wowjoy.office.data.response.AssetsCardQueryCondition;
import cn.wowjoy.office.data.response.InventoryAssetsCardQueryResponse;
import cn.wowjoy.office.databinding.ActivityCheckAddBinding;
import cn.wowjoy.office.utils.MyTextWatcher;
import cn.wowjoy.office.utils.ToastUtil;

public class CheckAddActivity extends NewBaseActivity<ActivityCheckAddBinding, CheckAddViewModel> implements View.OnClickListener {

    private MDialog waitDialog;
    private AutoEditAdapter autoEditAdapter;
    private BottomMenuPopupType mMenuPop;

    private AutoKeyPopup mKeyPopup;

    private boolean isClick;

    private AssetsCardQueryCondition addEntity;
    private String taskId;

    private TextWatcher watcher;
    MDialog submitDialog;

    private   String categoryId;
    @Override
    protected Class<CheckAddViewModel> getViewModel() {
        return CheckAddViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_add;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);

        mHandler = new MyHandler(this, viewModel);
        binding.addTitle.titleTextTv.setText("设置盘盈");
        binding.addTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.addTitle.titleBackTv.setText("");
        binding.addTitle.titleBackLl.setOnClickListener(this);
        binding.addTitle.titleMenuConfirm.setText("保存");
        binding.addTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.addTitle.titleMenuConfirm.setOnClickListener(this);
        taskId = getIntent().getStringExtra("taskId");
        initView();
        initEditListener();
        initObserve();

    }

    private void initObserve() {
        viewModel.getQuery().observe(this, new Observer<LiveDataWrapper<InventoryAssetsCardQueryResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InventoryAssetsCardQueryResponse> inventoryAssetsCardQueryResponseLiveDataWrapper) {
                assert inventoryAssetsCardQueryResponseLiveDataWrapper != null;
                switch (inventoryAssetsCardQueryResponseLiveDataWrapper.status) {
                    case LOADING:
//                        waitDialog = CreateDialog.waitingDialog(CheckAddActivity.this);
                        break;
                    case SUCCESS:
//                        if (null != waitDialog) {
//                            CreateDialog.dismiss(CheckAddActivity.this, waitDialog);
//                        }
                        //获取List模糊集合
                        if (inventoryAssetsCardQueryResponseLiveDataWrapper.data != null) {
                            List<AssetsCardQueryCondition> detailList = inventoryAssetsCardQueryResponseLiveDataWrapper.data.getDetailList();
                            if (null == mKeyPopup) {
                                mKeyPopup = new AutoKeyPopup(CheckAddActivity.this);
                                mKeyPopup.setAdapter(viewModel.mAutoEditAdapter);
                            }
                            if (!"0".equals(inventoryAssetsCardQueryResponseLiveDataWrapper.data.getTotalCount())) {
                                mKeyPopup.setDates(detailList);
                                mKeyPopup.showAsDropDown(binding.tvCardNo,0,1);
                            }else{
                                if (mKeyPopup != null && mKeyPopup.isShowing()) {
                                    mKeyPopup.dismiss();
                                }
                            }

                        }
                        break;
                    case ERROR:
//                        if (null != waitDialog) {
//                            CreateDialog.dismiss(CheckAddActivity.this, waitDialog);
//                        }
//                        handleException(inventoryAssetsCardQueryResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });
        viewModel.getClick().observe(this, new Observer<AssetsCardQueryCondition>() {
            @Override
            public void onChanged(@Nullable AssetsCardQueryCondition assetsCardQueryCondition) {
                hideSoftInput();
                if (null != mKeyPopup) {
                    mKeyPopup.dismiss();
                }
                binding.tvCardNo.removeTextChangedListener(watcher);
                addEntity = assetsCardQueryCondition;
                //更新UI界面
                if (null != assetsCardQueryCondition && !"".equals(assetsCardQueryCondition.getProduceNo())) {
                    binding.tvCardNo.setText(assetsCardQueryCondition.getProduceNo());
                    binding.tvCardNo.setSelection(binding.tvCardNo.getText().length());
                }
                if (null != assetsCardQueryCondition && !"".equals(assetsCardQueryCondition.getAssetsSpec())) {
                    binding.tvCardModelQuery.setText(assetsCardQueryCondition.getAssetsSpec());
                }
                if (null != assetsCardQueryCondition && !"".equals(assetsCardQueryCondition.getCardName())) {
                    binding.tvCardNameQuery.setText(assetsCardQueryCondition.getCardName());
                }
                if (null != assetsCardQueryCondition && !"".equals(assetsCardQueryCondition.getCategoryName())) {
                    binding.tvDeviceTypeQuery.setText(assetsCardQueryCondition.getCategoryName());
                }
                binding.rlLook.setVisibility(View.GONE);
                binding.rlGuige.setVisibility(View.GONE);
                binding.rlZichan.setVisibility(View.GONE);
                binding.mainQuery.setVisibility(View.VISIBLE);

                binding.tvCardName.setText("");
                binding.tvCardModel.setText("");
                binding.tvType.setText("");
                binding.tvType.setHint("请选择");

                binding.tvCardNo.addTextChangedListener(watcher);
            }
        });

        viewModel.getSubmit().observe(this, new Observer<LiveDataWrapper<Boolean>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                        switch (booleanLiveDataWrapper.status) {
                            case LOADING:
                                waitDialog = CreateDialog.waitingDialog(CheckAddActivity.this);
                                break;
                            case SUCCESS:
                                if (null != waitDialog) {
                                    CreateDialog.dismiss(CheckAddActivity.this, waitDialog);
                                }
                                finish();
                                break;
                            case ERROR:
                                if (null != waitDialog) {
                                    CreateDialog.dismiss(CheckAddActivity.this, waitDialog);
                                }
                                Throwable throwable = booleanLiveDataWrapper.error;
                                    submitDialog = CreateDialog.submitDialog(CheckAddActivity.this, "新增失败", throwable.getMessage(), 101, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            submitDialog.cancel();
                                            finish();
                                        }
                                    }, "确定");
//                                    handleException(throwable,false);
                                break;
                        }
            }
        });
    }

    private void initView() {
        binding.beizhu.setText(Html.fromHtml(getString(R.string.divice_notice8)));
        binding.zichanmingcheng.setText(Html.fromHtml(getString(R.string.divice_notice5)));
        binding.xinghao.setText(Html.fromHtml(getString(R.string.divice_notice6)));
        binding.leibie.setText(Html.fromHtml(getString(R.string.divice_notice7)));

        binding.zichanmingchengQuery.setText(Html.fromHtml(getString(R.string.divice_notice5)));
        binding.xinghaoQuery.setText(Html.fromHtml(getString(R.string.divice_notice6)));
        binding.leibieQuery.setText(Html.fromHtml(getString(R.string.divice_notice7)));
    }

    long timeStart;
    long timeAfter;

    private void initEditListener() {
        binding.rlLook.setOnClickListener(this);

        binding.tvCardNo.addTextChangedListener(new MyTextWatcher(binding.tvLimitCardNo, binding.tvCardNo, 25, CheckAddActivity.this));
        binding.tvCardName.addTextChangedListener(new MyTextWatcher(binding.tvLimitCardName, binding.tvCardName, 25, CheckAddActivity.this));
        binding.tvCardModel.addTextChangedListener(new MyTextWatcher(binding.tvLimitCardModel, binding.tvCardModel, 25, CheckAddActivity.this));
        binding.remark.addTextChangedListener(new MyTextWatcher(binding.tvLimit, binding.remark, 100, CheckAddActivity.this));
//        binding.tvCardNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//
//                return false;
//            }
//        });
        watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {


                    binding.rlLook.setVisibility(View.VISIBLE);
                    binding.rlGuige.setVisibility(View.VISIBLE);
                    binding.rlZichan.setVisibility(View.VISIBLE);
                    binding.mainQuery.setVisibility(View.GONE);
                    addEntity = null;

                if (mHandler.hasMessages(MSG_SEARCH)) {
                    mHandler.removeMessages(MSG_SEARCH);
                }
                //联网请求模糊数据
                if (!s.toString().trim().isEmpty()) {
                    Message message = mHandler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("data", s.toString().trim());// 将服务器返回的订单号传到Bundle中，，再通过handler传出
                    message.setData(bundle);
                    message.what = MSG_SEARCH;
                    mHandler.sendMessageDelayed(message, 1000);
//                    viewModel.getQueryList(s.toString().trim());
                }else{
                    //  搜索清空的时候
                    if (mKeyPopup != null && mKeyPopup.isShowing()) {
                        mKeyPopup.dismiss();
                    }
                }
            }
        };
        binding.tvCardNo.addTextChangedListener(watcher);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back_ll:
                finish();
                break;
            case R.id.title_menu_confirm:
                SubmitCheckTaskListDetailRequest request = new SubmitCheckTaskListDetailRequest();

                // 保存新增      * 先判空操作    1.手动填写的    2.自动更新填写的
                if (0 == binding.tvCardNo.getText().length()) {
                    ToastUtil.toastWarning(CheckAddActivity.this, "请填写出厂编码", -1);
                    return;
                }
                if (binding.rlZichan.getVisibility() == View.VISIBLE && 0 == binding.tvCardName.getText().length()) {
                    ToastUtil.toastWarning(CheckAddActivity.this, "请填写资产名称", -1);
                    return;
                }
                if (binding.rlGuige.getVisibility() == View.VISIBLE && 0 == binding.tvCardModel.getText().length()) {
                    ToastUtil.toastWarning(CheckAddActivity.this, "请填写规格型号", -1);
                    return;
                }
                if (binding.rlLook.getVisibility() == View.VISIBLE && 0 == binding.tvType.getText().length()) {
                    ToastUtil.toastWarning(CheckAddActivity.this, "请选择资产类别", -1);
                    return;
                }
                if (binding.rlRemarkNodone.getVisibility() == View.VISIBLE && 0 == binding.remark.getText().length()) {
                    ToastUtil.toastWarning(CheckAddActivity.this, "请填写盘盈说明", -1);
                    return;
                }
                if (null != taskId) {
                    request.setBillId(taskId);
                }
                String remark = binding.remark.getText().toString().trim();
                String encode = null;
                try {
                    encode = URLEncoder.encode(remark, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                request.setRemarks(encode);
                if (binding.mainQuery.getVisibility() == View.GONE && binding.rlZichan.getVisibility() == View.VISIBLE) {
                    //手动填写 提交
                    request.setInventoryQuantity("1");
                    request.setBookQuantity("0");
                    request.setProduceNo(binding.tvCardNo.getText().toString().trim());
                    request.setCardName(binding.tvCardName.getText().toString().trim());
                    request.setCategoryId(categoryId);
                    request.setAssetsSpec(binding.tvCardModel.getText().toString().trim());
                    viewModel.submitDetail(request, true);
                } else if (binding.mainQuery.getVisibility() == View.VISIBLE && binding.rlZichan.getVisibility() == View.GONE) {
                    // 有一种情况  他自动更新了下  然后删除了几个编码  保存？？
                    if (null != addEntity) {
//                        Log.e("PXY", "onClick: " + addEntity.toString());
                        request.setCardNo(addEntity.getCardNo());
                        request.setAssetsSpec(addEntity.getAssetsSpec());
                        request.setCategoryId(addEntity.getCategoryId());
                        request.setProduceNo(addEntity.getProduceNo());
                        request.setCardVersionId(addEntity.getCardVersionId());
                        request.setInventoryQuantity("1");
                        request.setBookQuantity("0");
                        request.setCardName(addEntity.getCardName());
                        viewModel.submitDetail(request, true);
                    }
                }
                break;
            case R.id.rl_look:
                Intent intent = new Intent(CheckAddActivity.this, CategoryActivity.class);
                if ("".equals(binding.tvType.getText().toString().trim())) {
                    intent.putExtra("name", "");
                } else {
                    intent.putExtra("name", binding.tvType.getText().toString().trim());
                }
                startActivityForResult(intent, Constants.REQUEST_CODE);
                break;
//            case R.id.rl_look:
//                if (null == mMenuPop) {
//                    mMenuPop = new BottomMenuPopupType(CheckAddActivity.this, itemsOnClick_OutAdded, binding.tvType.getText().toString());
//                    mMenuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                        @Override
//                        public void onDismiss() {
//                            AlphaManager.backgroundAlpha(1f, CheckAddActivity.this);
//                        }
//                    });
//                }
//                //显示窗口
//                mMenuPop.showAtLocation(CheckAddActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
//                AlphaManager.backgroundAlpha(0.7f, CheckAddActivity.this);
//                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mKeyPopup) {
            mKeyPopup.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constants.RESULT_OK:
                //选择了
                binding.tvType.setText(data.getStringExtra("name"));
                categoryId = data.getStringExtra("categoryId");
                break;
            case Constants.RESULT_FAIL:

                break;
        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick_OutAdded = new View.OnClickListener() {

        public void onClick(View v) {
            if (null != mMenuPop && mMenuPop.isShowing()) {
                mMenuPop.dismiss();
            }
            switch (v.getId()) {
                case R.id.rl_fixed:
                    binding.tvType.setText("固定资产");
                    mMenuPop.setRight("固定资产");
                    AlphaManager.backgroundAlpha(1.0f, CheckAddActivity.this);
                    break;
                case R.id.rl_lowValue:
                    binding.tvType.setText("低值易耗");
                    mMenuPop.setRight("低值易耗");
                    AlphaManager.backgroundAlpha(1.0f, CheckAddActivity.this);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mKeyPopup != null && mKeyPopup.isShowing()) {
            mKeyPopup.dismiss();
            mKeyPopup = null;
        }
        return super.onTouchEvent(event);
    }


    private static final int MSG_SEARCH = 1;
    private Handler mHandler;

    static class MyHandler extends Handler {
        // WeakReference to the outer class's instance.
        private WeakReference<CheckAddActivity> mOuter;
        private CheckAddViewModel mCheckAddViewModel;

        public MyHandler(CheckAddActivity activity, CheckAddViewModel vm) {
            mOuter = new WeakReference<CheckAddActivity>(activity);
            this.mCheckAddViewModel = vm;
        }

        @Override
        public void handleMessage(Message msg) {
            CheckAddActivity outer = mOuter.get();
            if (outer != null) {
                if (msg.what == MSG_SEARCH) {
                    mCheckAddViewModel.getQueryList(msg.getData().getString("data"));
                }
            }
        }
    }
}
